<?php
require_once( 'Zend/Controller/Action.php');
require_once( 'Zend/Db.php' );
require_once( 'Zend/Db/Table.php' );
require_once( 'Zend/Db/Table/Abstract.php' );
require_once( 'models/Paciente.php');
require_once( 'modules/default/Form/Form.php');
require_once( 'IndexController.php');
require_once( 'Zend/Exception.php');
require_once( 'InitController.php');
class PacienteController extends InitController {
	
	private $connection;
	
	protected $_auth = null;
 
 
   	
    public function insertAction() {
    	$this->view->title = 'Medisoft - Paciente';
    	$this->view->identity = $this->_auth->getIdentity();
    	
    	       
        $request = $this->getRequest();
        $this->view->assign('action', $request->getBaseURL()."/paciente/ins-paciente"); 
        $form = $this->getPacForm();
    	$this->view->form = $form;
    }
    
   
	public function insPacienteAction() {
		
	
		$request = $this->getRequest();

        // Check if we have a POST request
        if ($request->isPost()) {
            
        

        	// Get our form and validate it
        	
        	$form = $this->getPacForm();
        	if (!$form->isValid($request->getPost())) {
        	    // Invalid entries
        	    $this->view->form = $form;
        	    return $this->render('insert'); // re-render the form
        	}
		
		
        $this->view->title = 'Medisoft - Insertar Paciente';
		$pac = new PACIENTE();
		
    	//Cargo los parametros
		$pac->nombre=$_POST['nombre'];
		$pac->apellido=$_POST['apellido'];
		$pac->dni=(int)$_POST['dni'];
		$pac->sexo=$_POST['sexo'];
		$pac->peso=(int)$_POST['peso'];
		$pac->date=$_POST['date'];
		$pac->direccion=$_POST['direccion'];
		$pac->osocial=$_POST['osocial'];
		$pac->nroafiliado=(int)$_POST['nroafiliado'];
		$pac->plan=$_POST['plan'];
		$pac->fechaprimer=date('Y-m-d');
		
		
        
		
			$state=$pac->insPacientes();
			if ( $state === $pac->dni ){
				$this->view->message = "El Paciente ha sido agregado con éxito";
			}
			else 
				$this->view->message = "No se pudo agregar el Paciente";
        }
        else
        	$this->_forward('insert');
		
    }
    
    public function listPacientesAction() {
    	Zend_Loader::loadClass('Paciente', 'models');
    	
    	
    	$this->view->title = 'Medisoft - Listar';
    	$request = $this->getRequest();

        // Check if we have a POST request
        
    	$pac = new PACIENTE();
    	if ($request->isPost()) {
        	
    	$pac->nombre=$_POST['nombre'];
    	$pac->apellido=$_POST['apellido'];
    	$pac->dni=$_POST['dni'];
    	$pac->osocial=$_POST['osocial'];
    	}
    	else
    	{
    	$pac->nombre='';
    	$pac->apellido='';
    	$pac->dni='';
    	$pac->osocial='';
    	}
        $this->view->pacs = $pac->listPacientes();
        
        $form = $this->getsearchform();
		$this->view->forms = $form;
        return $this->render('index');
    	
    }
    
	public function indexAction() {
    	Zend_Loader::loadClass('Paciente', 'models');
    	
    	$this->view->title = 'Medisoft - Buscar';
    	$pac = new PACIENTE();
    	$this->view->pacs = $pac->listallPacientes();
    	
    	$form = $this->getsearchform();
		$this->view->forms = $form;
    	    	
    }
    
    public function modPacientesAction() {
    	//if($_POST['submit']=="Borrar")
    	if(!empty($_POST['Borrar']))
        {
        	$this->view->title = 'Medisoft - Borrar';
        	$pac = new PACIENTE();
        	$pac->dni = $_POST['paciente'];
        	$result=$pac->delPacientes();
        	if ($result == 0)
        	{
        		$this->view->message = "No se pudo borrar el paciente ". $pac->dni;
        		$this->view->title = 'Medisoft - Buscar';
    			$pac = new PACIENTE();
    			$this->view->pacs = $pac->listallPacientes();
    	
    			$form = $this->getsearchform();
    			$this->view->forms = $form;
        		return $this->render('index');
        	}
        	else
        	{
        	 	$this->view->message = "Paciente ".$pac->dni . " borrado con éxito";
        	 	$this->view->title = 'Medisoft - Buscar';
    			$pac = new PACIENTE();
    			$this->view->pacs = $pac->listallPacientes();
    	
    			$form = $this->getsearchform();
    			$this->view->forms = $form;
        	 	return $this->render('index');
        	}
        }

		else if (!empty($_POST['Modificar']))
        {
        	$this->view->title = 'Medisoft - Modificar';
        	$this->view->update = 1;
        	
        	        	
        	$pac = new PACIENTE();
        	$pac->dni = $_POST['paciente'];
        	$this->view->auxdni = $pac->dni;
        	$pac->param="PDNI";
    		$pac->data=$pac->dni;
        	$this->view->pacs = $pac->showPaciente();
        	foreach ($this->view->pacs as $pacs) {
        	if ($pacs->PSEXO == "M")
        		$this->view->sexo = "Masculino";
        	else
        		$this->view->sexo = "Femenino";      		
        	}
        	$request = $this->getRequest();
        	$this->view->assign('action', $request->getBaseURL()."/paciente/update-pacientes");
        	
        	$form = $this->getPacForm();
        	foreach ($this->view->pacs as $pacs) {
        		$data['nombre'] = $pacs->PNOMBRE_PACIENTE;
        		$data['apellido'] = $pacs->APELLIDO_PACIENTE;
        		$data['dni'] = $pacs->PDNI;
        		$data['sexo'] = $pacs->PSEXO;
        		$data['peso'] = $pacs->PPESO;
        		$data['fecha_nac'] = $pacs->PFECHA_DE_NAC;
        		$data['direccion'] = $pacs->PDOMICILIO;
        		$data['osocial'] = $pacs->POBRA_SOCIAL;
				$data['nroafiliado'] = $pacs->PNRO_AFILIADO;
				$data['plan'] = $pacs->PPLAN;
				$data['auxdni'] =$pac->dni;
        	}
        	 
        	$form->populate($data);
        	$this->view->form = $form;
        }
        else
        	$this->_forward('index');
    }
	public function updatePacientesAction() {
		$request = $this->getRequest();

        // Check if we have a POST request
        if ($request->isPost()) {
            
        

        	// Get our form and validate it
        	
        	$form = $this->getPacForm();
        	if (!$form->isValid($request->getPost())) {
        	    // Invalid entries
        	    $this->view->form = $form;
        	    $this->view->update = 1;
        	    return $this->render('mod-pacientes'); // re-render the form
        	}
		
    	Zend_Loader::loadClass('Paciente', 'models');
    	$this->view->title = 'Medisoft - Update';
    	
		
    	$pac = new PACIENTE();
    		
    	//Cargo los parametros
		$pac->nombre=$_POST['nombre'];
		$pac->apellido=$_POST['apellido'];
		$pac->dni=(int)$_POST['dni'];
		$pac->sexo=$_POST['sexo'];
		$pac->peso=(int)$_POST['peso'];
		$pac->date=$_POST['date'];
		$pac->direccion=$_POST['direccion'];
		$pac->osocial=$_POST['osocial'];
		$pac->nroafiliado=(int)$_POST['nroafiliado'];
		$pac->plan=$_POST['plan'];
		$pac->fechaprimer=date('Y-m-d');
		$pac->auxdni=$_POST['auxdni'];
			 	
		
			$state=$pac->updatePacientes();
			if ( $state === 1 )
				$this->view->message = "El Paciente ha sido actualizado con éxito";
			else 
				$this->view->message = "No se pudo actualizar el Paciente";
        }
        else
        	$this->_forward('index');
    }
    
	private function getPacForm() {
		$form = new Zend_Form();
		$form->setAction($this->view->action)->setMethod('post');
		
		$decoradores = array(
		'ViewHelper',
		'Errors',
     	array('HtmlTag', array('tag' => 'div', 'class' =>'b')),
     	array('Label', array('requiredSuffix'=>'*')),
     	//array('Fieldset', array('tag' =>'fset'))
     	//array('ViewScript', array('viewScript' => 'decorador-contenedor.phtml', 'placement' => false))
		);
		
		$decoradoresb = array(
		'ViewHelper',
		'Errors',
     	array('HtmlTag', array('tag' => 'divc', 'class' => 'a'))
		);
		
		$decoradoresc = array(
		'ViewHelper',
		'Errors',
     	array('HtmlTag', array('tag' => 'divc', 'class' => 'b'))
		);

		

    		  
		// Create and configure username element:
		$pacname = $form->createElement('text', 'nombre', array('label' => 'Nombre'));
		$pacname->addValidator('regex', false, array('/^([a-zA-Z]|" ")+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		$pacap = $form->createElement('text', 'apellido', array('label' => 'Apellido'));
		$pacap->addValidator('regex', false, array('/^([a-zA-Z]|" ")+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		         
		$pacdni = $form->createElement('text', 'dni', array('label' => 'DNI'));
		$pacdni->addValidator('alnum')
		         ->addValidator('regex', false, array('/^[0-9]+/'))
		         ->addValidator('stringLength', false, array(1, 10))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		$pacsex = $form->createElement('select', 'sexo', array('label' => 'Sexo',  'value' => 'sexo', 'multiOptions' => array(
                 'M'=>'Masculino', 'F'=>'Femenino')));
		$pacsex->setDecorators($decoradores)
				->setRequired(true);
		         
		         
		$pacpeso = $form->createElement('text', 'peso', array('label' => 'Peso'));
		$pacpeso->addValidator('alnum')
		         ->addValidator('regex', false, array('/^[0-9]+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		$pacfecha = $form->createElement('text', 'fecha_nac', array('label' => 'Fecha de Nacimiento','value' => 'YYYY-MM-DD'));
		$pacfecha->addValidator('date')
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		$pacdir = $form->createElement('text', 'direccion', array('label' => 'Direccion'));
		$pacdir->addValidator('regex', false, array('/^([a-zA-Z]|" ")+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setRequired(true)
		         ->setDecorators($decoradores)
		         ->addFilter('StringToLower');
		         
		$pacobrasoc = $form->createElement('select', 'osocial', array('label' => 'Obra Social',  'value' => 'obrasoc', 'multiOptions' => array(
                 'SMG'=>'SMG', 'OSDE'=>'OSDE', 'Galeno'=>'Galeno')));
		$pacobrasoc->setDecorators($decoradores);
				         
		$pacnroaf = $form->createElement('text', 'nroafiliado', array('label' => 'Nro. de Afiliado'));
		$pacnroaf->addValidator('alnum')
		         ->addValidator('regex', false, array('/^([a-z]*|[0-9]*)+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setDecorators($decoradores)
				 ->addFilter('StringToLower');
		         
		$pacplan = $form->createElement('text', 'plan', array('label' => 'Plan'));
		$pacplan->addValidator('alnum')
		         ->addValidator('regex', false, array('/^[a-z]+/'))
		         ->addValidator('stringLength', false, array(1, 30))
		         ->setDecorators($decoradores)
				->addFilter('StringToLower');
		         
		$auxdni = $form->createElement('text', 'dni', array('label' => 'DNI'));
		$auxdni->addValidator('alnum')
		         ->addValidator('regex', false, array('/^[0-9]+/'))
		         ->addValidator('stringLength', false, array(1, 10))
		         ->setDecorators($decoradores)
				 ->addFilter('StringToLower');
		         
		$pacres = $form->createElement('reset', 'reset', array('label' => 'Reset'));
		$pacres->setDecorators($decoradoresb);
		$pacsub = $form->createElement('submit', 'ingresar', array('label' => "Ingresar"));
		$pacsub->setDecorators($decoradoresc);
		
		$date = new Zend_Dojo_Form_Element_DateTextBox('date');
        $date->setLabel('Fecha de Nacimiento');
        $date->setInvalidMessage('La fecha ingresada es inválida');
        $date->setPromptMessage('mm-dd-yyyy');
        $date->setRequired(true);
		
		// Add elements to form:
		$form->addElement($pacname)
		     ->addElement($pacap)
			 ->addElement($pacdni)
		     ->addElement($pacsex)
		     ->addElement($pacpeso)
		     ->addElement($date)
		     ->addElement($pacdir)
		     ->addDisplayGroup(array('nombre', 'apellido','dni','sexo','peso','date','direccion'), 'Infop', array("legend" => "Info Personal"))
		     ->addElement($pacobrasoc)
		     ->addElement($pacnroaf)
		     ->addElement($pacplan)
		     ->addDisplayGroup(array('osocial', 'nroafiliado','plan'), 'Infos', array("legend" => "Info Social"))
		     ->addElement('hidden', 'auxdni', array('values' => ''))
		     ->addElement($pacres)
		     ->addElement($pacsub);
		     //->addElement('submit', 'ingresar', array('label' => "Ingresar"));
		$form->setAttrib('onsubmit',"return confirm('¿Está seguro que quiere Ingresar los datos del Paciente?')");     		     
    	return $form;
    }
    public function getsearchform() {
    	
    	$form = new Zend_Form();
		$form->setAction("/index.php/paciente/list-pacientes")->setMethod('post');
		
		
		$decoradoresb = array(
		'ViewHelper',
		'Errors',
     	array('HtmlTag', array('tag' => 'divc', 'class' => 'a'))
		);
		
		$decoradoresc = array(
		'ViewHelper',
		'Errors',
     	array('HtmlTag', array('tag' => 'divc', 'class' => 'b'))
		);
		
		$nombre = $form->createElement('text', 'nombre', array('label' => 'Nombre', 'value'=>''));
		
		$apellido = $form->createElement('text', 'apellido', array('label' => 'Apellido', 'value'=>''));
		
		$dni = $form->createElement('text', 'dni', array('label' => 'DNI', 'value'=>''));
		
		$osocial = $form->createElement('select', 'osocial', array('label' => 'Obra Social',  'value' => '', 'multiOptions' => array(
                 ''=>'', 'SMG'=>'SMG', 'OSDE'=>'OSDE', 'Galeno'=>'Galeno')));
		
		
				
		$pacmod = $form->createElement('submit', 'Buscar', array('label' => 'Buscar'));
		//$pacmod->setDecorators($decoradoresb);
		//$pacdel = $form->createElement('reset', 'reset', array('label' => "Reset"));
		//$pacdel->setDecorators($decoradoresc);
		
    	$form->addElement($nombre);
    	$form->addElement($apellido);
    	$form->addElement($dni);
    	$form->addElement($osocial);
		$form->addElement($pacmod);
		//$form->addElement($pacdel)
		$form->addDisplayGroup(array('nombre', 'apellido','dni','osocial','Buscar'), 'buscar', array("legend" => "Buscar Paciente"));
		
		return $form;
    	
    }

    
}